// 数据库操作
const mongoose = require('mongoose');
// 模型规则类
const {
    Schema
} = mongoose;

// 对象规则验证
const Joi = require('joi');
// 房间模型规则
const roomSchema = new Schema({
    // 房间号
    tag: {
        type: String,
        required: [true, '房间号不能为空'],
        unique: [true, '房间号已存在'],
        minlength: 3,
        maxlength: 5
    },
    // 房型ID
    type: {
        type: mongoose.Schema.Types.ObjectId,
        default: null,
        ref: 'RoomType'
    },
    // 房间拥有的床位
    beds: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Bed'
    }],
    isBedMode: {
        type: Boolean,
        required: true,
        default: false
    },
    floor: {
        type: Number,
        required: [true, '楼层不能为空'],
        default: 1,
        min: 1,
        max: 99
    },
    owner: {
        type: String
    },
    building: {
        type: String
    },
    facilities: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Facility'
    }],
    comment: {
        type: String
    }
}, {
    versionKey: false
});

const Room = mongoose.model('Room', roomSchema);

// 房间格式校验
const validateRoom = room => {
    // 定义对象验证规则
    const schema = {
        tag: Joi.string().regex(/^[\d][\d-]{2,4}$/).required().error(new Error("[房间号]格式错误，必须以数字开头，可包含数字和分隔符'-'，长度为3~5位")),
        floor: Joi.number().min(1).max(99).required().error(new Error("楼层参数不能为空")),
        isBedMode: Joi.boolean().required().error(new Error("是否按床位售卖标识项不能为空"))
    };
    // 验证
    return Joi.validate(room, schema, {
        // 检测到所有错误
        abortEarly: false,
        // 允许对象包含被忽略的未知键
        allowUnknown: true
    });
}

// 导出模块成员
module.exports = {
    Room,
    validateRoom
}